package com.lkd.job;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.SkuEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.entity.VmPolicyEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.SkuService;
import com.lkd.service.VendingMachineService;
import com.lkd.service.VmPolicyService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class TimingscanXxlJob {
    @Autowired
    private SkuService skuService;

    @Autowired
    private MqttProducer mqttProducer;
    @Autowired
private VendingMachineService vendingMachineService;
    @Autowired
    private ChannelService channelService;
    @XxlJob("TimingscanXxlJobHandler")
    public void timingScan()
    {
        List<VendingMachineEntity> list = vendingMachineService.list();
        assert list!=null;
        list.stream().forEach(vendingMachineEntity -> {
            List<ChannelEntity> channelesByInnerCode = channelService.getChannelesByInnerCode(vendingMachineEntity.getInnerCode());
            assert channelesByInnerCode!=null;
            //補貨策略
            channelesByInnerCode.stream().forEach(this::supplement);
        });
    }

    /**
     * 補貨策略
     * @param channelEntity
     */
    private void supplement(ChannelEntity channelEntity) {
        assert  channelEntity!=null;
        // 獲取發送對象
        SupplyContract supplyContract = channelEntity.getMaxCapacity() - channelEntity.getCurrentCapacity() >= 5 ?
                supplementgoods(channelEntity) : null;

        try {
            mqttProducer.send("",2,supplyContract);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("協議異常");
        }
    }

    /**
     * 設置補貨協議
     * @param channelEntity
     * @return
     */
    private SupplyContract supplementgoods(ChannelEntity channelEntity) {
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(channelEntity.getInnerCode());
        SkuEntity skuEntity = skuService.find(channelEntity.getSkuId());
        SupplyChannel supplyChannel = new SupplyChannel();
        supplyChannel.setChannelId(channelEntity.getChannelCode());
        supplyChannel.setCapacity(channelEntity.getMaxCapacity()-channelEntity.getCurrentCapacity());
        BeanUtils.copyProperties(skuEntity,supplyChannel);
        List<SupplyChannel> data = new ArrayList<>();
        data.add(supplyChannel);
        supplyContract.setSupplyData(data);
        return supplyContract;
    }
}
